// 商品相关路由配置

const Router = require('@koa/router');
const mongoose = require('mongoose');
const GoodModel = mongoose.model('Good');
const InventoryLogModel = mongoose.model('InventoryLog');

const router = new Router({
  prefix: '/good',
});

// 添加商品接口
router.post('/add', async (ctx) => {
  console.log('--> 调用接口 post /book/add');
  console.log(ctx.request.body);
  const { name, price, merchant, publishDate, classify, count } = ctx.request.body;
  const good = new GoodModel({ name, price, merchant, publishDate, classify, count });
  const res = good.save();
  ctx.body = {
    msg: '新增商品成功',
    code: 1,
    data: res,
  };
});

// 删除商品接口
router.delete('/:id', async (ctx) => {
  const { id } = ctx.params;
  console.log(`--> 调用接口 delete /book/list/${id}`);
  const res = await GoodModel.deleteOne({
    _id: id,
  });
  ctx.body = {
    msg: '删除商品成功',
    code: 1,
    data: res,
  };
});

// 更新商品接口
router.post('/update', async (ctx) => {
  console.log('--> 调用接口 post /book/update');
  console.log(ctx.request.body);
  const { id, name, price, merchant, publishDate, classify } = ctx.request.body;
  const one = await GoodModel.findOne({ _id: id }).exec();
  if (!one) {
    ctx.body = {
      msg: '没有对应的商品',
      code: 0,
      data: null,
    };
    return;
  }

  const newInfo = { name, price, merchant, publishDate, classify };
  Object.assign(one, newInfo);
  const res = await one.save();

  ctx.body = {
    msg: '修改商品信息成功',
    code: 1,
    data: res,
  };
});

// 获取商品列表
router.get('/list', async (ctx) => {
  console.log('--> 调用接口 get /book/list');
  let { size = 3, page = 1, keyword = '' } = ctx.query;
  size = Number(size);
  page = Number(page);
  const goodlist = await GoodModel.find({
    name: {
      $regex: keyword,
    },
  })
    .sort({ _id: -1 })
    .skip((page - 1) * size)
    .limit(size)
    .exec();
  const total = await GoodModel.countDocuments();
  ctx.body = {
    msg: '获取商品列表成功',
    code: 1,
    data: {
      list: goodlist,
      total,
      page,
      size,
    },
  };
});

const COUNT_TYPE = {
  IN: 'IN',
  OUT: 'OUT',
};

// 出库、入库
router.post('/count', async (ctx) => {
  console.log(`--> 调用接口 post /good/count`);
  console.log(ctx.request.body);
  // 需要参数
  //   商品id
  //   类型:
  //     出库 IN
  //     入库 OUT
  //   数量
  let { id, type, num } = ctx.request.body;
  const good = await GoodModel.findOne({
    _id: id,
  }).exec();

  // 如果没有对应id的商品
  if (!good) {
    ctx.body = {
      msg: '商品不存在',
      code: 0,
      data: null,
    };
    return;
  }

  num = type === COUNT_TYPE.IN ? Math.abs(num) : -Math.abs(num);
  if (good.count + num < 0) {
    ctx.body = {
      msg: '剩下数量不足以出库',
      code: 0,
      data: null,
    };
    return;
  }
  good.count += num;
  const res = await good.save();

  const log = new InventoryLogModel({
    type,
    num: Math.abs(num),
    userId: res._id,
  });

  await log.save();

  ctx.body = {
    msg: `${type === COUNT_TYPE.IN ? '入库' : '出库'}成功，数量：${Math.abs(num)}`,
    code: 1,
    data: res,
  };
});

const findGood = async (id) => {
  const one = await GoodModel.findOne({ _id: id }).exec();
  return one;
};

// 商品详情信息
router.get('/detail/:id', async (ctx) => {
  const { id } = ctx.params;
  console.log(`--> 调用接口 get /detail/${id}`);
  const good = await findGood(id);
  if (!good) {
    ctx.body = {
      msg: '获取商品详细信息失败，没有找到商品',
      code: 0,
      data: null,
    };
    return;
  }
  ctx.body = {
    msg: '获取商品详情信息成功',
    code: 1,
    data: good,
  };
});

module.exports = router;
